package com.usaas.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usaas.common.core.domain.AjaxResult;
import com.usaas.search.dto.PlatMessageCategoryDto;
import com.usaas.search.dto.PlatMessageDto;
import com.usaas.search.mapper.PlatMessageMapper;
import com.usaas.search.pojo.PlatMessageCategoryPojo;
import com.usaas.search.pojo.PlatMessagePojo;
import com.usaas.search.service.IPlatMessageCategoryService;
import com.usaas.search.service.IPlatMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 平台推广信息Service业务层处理
 *
 * @author Helios
 * @date 2024-08-14
 */
@Slf4j
@Service
public class PlatMessageServiceImpl extends ServiceImpl<PlatMessageMapper, PlatMessagePojo> implements IPlatMessageService {

    @Resource
    private PlatMessageMapper platMessageMapper;
    @Autowired
    private IPlatMessageCategoryService platMessageCategoryService;

    /**
     * 查询平台推广信息
     *
     * @param id 平台推广信息主键
     * @return 平台推广信息
     */
    @Override
    public PlatMessageDto queryById(Long id) {
        PlatMessagePojo pojo = this.getById(id);
        if (pojo != null) {
            PlatMessageDto dto = BeanUtil.copyProperties(pojo, PlatMessageDto.class);
            List<PlatMessageDto> dtos = ListUtil.of(dto);
            convertList(dtos);
            return dtos.get(0);
        }
        return null;
    }

    /**
     * 查询平台推广信息列表
     *
     * @param platMessageDto 平台推广信息
     * @return 平台推广信息
     */
    @Override
    public List<PlatMessageDto> queryList(PlatMessageDto platMessageDto) {
        LambdaQueryWrapper<PlatMessagePojo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = this.buildWrapper(queryWrapper, platMessageDto);
        if (queryWrapper == null) {
            return null;
        }
        List<PlatMessagePojo> list = this.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }

        List<PlatMessageDto> dtoList = BeanUtil.copyToList(list, PlatMessageDto.class);
        convertList(dtoList);
        return dtoList;
    }

    private void convertList(List<PlatMessageDto> dtoList) {
        if (CollectionUtil.isEmpty(dtoList)) {
            return;
        }
        List<Long> messageIdList = dtoList.stream().map(e -> e.getId()).collect(Collectors.toList());
        LambdaQueryWrapper<PlatMessageCategoryPojo> categoryPojoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryPojoLambdaQueryWrapper.in(PlatMessageCategoryPojo::getMessageId, messageIdList);
        List<PlatMessageCategoryPojo> categoryList = platMessageCategoryService.list(categoryPojoLambdaQueryWrapper);
        if (CollectionUtil.isEmpty(categoryList)) {
            return;
        }
        List<PlatMessageCategoryDto> categoryDtoList = BeanUtil.copyToList(categoryList, PlatMessageCategoryDto.class);
        Map<Long, List<PlatMessageCategoryDto>> messageCategoryMap = categoryDtoList.stream()
                .collect(Collectors.groupingBy(PlatMessageCategoryDto::getMessageId));
        for (PlatMessageDto platMessageDto : dtoList) {
            Long id = platMessageDto.getId();
            List<PlatMessageCategoryDto> categoryDtoListTemp = messageCategoryMap.get(id);
            platMessageDto.setPlatMessageCategoryList(categoryDtoListTemp);
        }
    }

    /**
     * 新增平台推广信息
     *
     * @param platMessageDto 平台推广信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean add(PlatMessageDto platMessageDto) {
        PlatMessagePojo platMessagePojo = BeanUtil.copyProperties(platMessageDto, PlatMessagePojo.class);
        boolean save = this.save(platMessagePojo);
        Long messageId = platMessagePojo.getId();
        List<PlatMessageCategoryDto> platMessageCategoryList = platMessageDto.getPlatMessageCategoryList();
        updateMessageCategory(messageId, platMessageCategoryList);
        return save;
    }

    private void updateMessageCategory(Long messageId, List<PlatMessageCategoryDto> platMessageCategoryList) {
        if (CollectionUtil.isNotEmpty(platMessageCategoryList)) {
            //清空之前设置的类型
            LambdaQueryWrapper<PlatMessageCategoryPojo> removeWrapper = new LambdaQueryWrapper<>();
            removeWrapper.eq(PlatMessageCategoryPojo::getMessageId, messageId);
            platMessageCategoryService.remove(removeWrapper);
            //设置最新的
            for (PlatMessageCategoryDto platMessageCategoryDto : platMessageCategoryList) {
                platMessageCategoryDto.setMessageId(messageId);
            }
            List<PlatMessageCategoryPojo> platMessageCategoryPojos = BeanUtil.copyToList(platMessageCategoryList, PlatMessageCategoryPojo.class);
            platMessageCategoryService.saveBatch(platMessageCategoryPojos);
        }
    }

    /**
     * 修改平台推广信息
     *
     * @param platMessageDto 平台推广信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean update(PlatMessageDto platMessageDto) {
        PlatMessagePojo platMessagePojo = BeanUtil.copyProperties(platMessageDto, PlatMessagePojo.class);
        boolean updated = this.updateById(platMessagePojo);
        Long messageId = platMessagePojo.getId();
        List<PlatMessageCategoryDto> platMessageCategoryList = platMessageDto.getPlatMessageCategoryList();
        updateMessageCategory(messageId, platMessageCategoryList);
        return updated;
    }

    /**
     * 批量删除平台推广信息
     *
     * @param ids 需要删除的平台推广信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public boolean removeBatch(List<String> ids) {
        List<Long> idsLong = ids.stream().map(Long::parseLong).collect(Collectors.toList());
        boolean ok = this.removeBatchByIds(idsLong);
        //清空之前设置的类型
        for (Long messageId : idsLong) {
            LambdaQueryWrapper<PlatMessageCategoryPojo> removeWrapper = new LambdaQueryWrapper<>();
            removeWrapper.eq(PlatMessageCategoryPojo::getMessageId, messageId);
            platMessageCategoryService.remove(removeWrapper);
        }
        return ok;
    }


    /**
     * 分页查询${subTable.functionName}信息
     *
     * @param platMessageDto
     * @return
     */
    @Override
    public AjaxResult queryPage(PlatMessageDto platMessageDto) {
        Page<PlatMessagePojo> page = new Page<>(platMessageDto.getPageNum(), platMessageDto.getPageSize());
        LambdaQueryWrapper<PlatMessagePojo> wrapper = new LambdaQueryWrapper<PlatMessagePojo>();
        //此处可做前置判断
        if (wrapper == null) {
            return AjaxResult.success(page);
        }
        wrapper = buildWrapper(wrapper, platMessageDto);
        if (wrapper == null) {
            return AjaxResult.success(page);
        }
        Page<PlatMessagePojo> pageResult = this.page(page, wrapper);
        Page<PlatMessageDto> finalResult = BeanUtil.copyProperties(pageResult, Page.class);
        List<PlatMessagePojo> records = pageResult.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            List<PlatMessageDto> dtos = BeanUtil.copyToList(records, PlatMessageDto.class);
            convertList(dtos);
            finalResult.setRecords(dtos);
        }
        return AjaxResult.success(finalResult);
    }

    private LambdaQueryWrapper<PlatMessagePojo> buildWrapper(LambdaQueryWrapper<PlatMessagePojo> wrapper, PlatMessageDto param) {
        log.info("buildPageWrapper param :{}", param);
        if (wrapper == null) {
            return null;
        }
        Long id = param.getId();
        if (id != null) {
            wrapper.eq(PlatMessagePojo::getId, id);
        }
        String mainTitle = param.getMainTitle();
        if (StrUtil.isNotBlank(mainTitle)) {
            wrapper.eq(PlatMessagePojo::getMainTitle, mainTitle);
        }
        String subTitle = param.getSubTitle();
        if (StrUtil.isNotBlank(subTitle)) {
            wrapper.eq(PlatMessagePojo::getSubTitle, subTitle);
        }
        String name = param.getName();
        if (StrUtil.isNotBlank(name)) {
            wrapper.eq(PlatMessagePojo::getName, name);
        }
        String icons = param.getIcons();
        if (StrUtil.isNotBlank(icons)) {
            wrapper.eq(PlatMessagePojo::getIcons, icons);
        }
        Long gameInfoId = param.getGameInfoId();
        if (gameInfoId != null) {
            wrapper.eq(PlatMessagePojo::getGameInfoId, gameInfoId);
        }
        String versionDate = param.getVersionDate();
        if (StrUtil.isNotBlank(versionDate)) {
            wrapper.eq(PlatMessagePojo::getVersionDate, versionDate);
        }
        String messageDesc = param.getMessageDesc();
        if (StrUtil.isNotBlank(messageDesc)) {
            wrapper.eq(PlatMessagePojo::getMessageDesc, messageDesc);
        }
        String contentDesc = param.getContentDesc();
        if (StrUtil.isNotBlank(contentDesc)) {
            wrapper.eq(PlatMessagePojo::getContentDesc, contentDesc);
        }
        Long stars = param.getStars();
        if (stars != null) {
            wrapper.eq(PlatMessagePojo::getStars, stars);
        }
        Long hotLevel = param.getHotLevel();
        if (hotLevel != null) {
            wrapper.eq(PlatMessagePojo::getHotLevel, hotLevel);
        }
        Long collectNums = param.getCollectNums();
        if (collectNums != null) {
            wrapper.eq(PlatMessagePojo::getCollectNums, collectNums);
        }
        Long clickNum = param.getClickNum();
        if (clickNum != null) {
            wrapper.eq(PlatMessagePojo::getClickNum, clickNum);
        }
        String createBy = param.getCreateBy();
        if (StrUtil.isNotBlank(createBy)) {
            wrapper.eq(PlatMessagePojo::getCreateBy, createBy);
        }
        Date createTime = param.getCreateTime();
        if (createTime != null) {
            wrapper.eq(PlatMessagePojo::getCreateTime, createTime);
        }
        String updateBy = param.getUpdateBy();
        if (StrUtil.isNotBlank(updateBy)) {
            wrapper.eq(PlatMessagePojo::getUpdateBy, updateBy);
        }
        Date updateTime = param.getUpdateTime();
        if (updateTime != null) {
            wrapper.eq(PlatMessagePojo::getUpdateTime, updateTime);
        }
        String remark = param.getRemark();
        if (StrUtil.isNotBlank(remark)) {
            wrapper.eq(PlatMessagePojo::getRemark, remark);
        }
        Long delFlag = param.getDelFlag();
        if (delFlag != null) {
            wrapper.eq(PlatMessagePojo::getDelFlag, delFlag);
        }
        log.info("buildPageWrapper result :{}", wrapper);
        return wrapper;
    }
}
